<template>
  <el-dialog v-model="visible" :title="title" width="1100" show-footer show-zoom resize :close-on-click-modal="false"
    :close-on-press-escape="false" @close="close">
    <template #default>
      <el-form ref="formRef" :rules="rules" :model="form" label-align="right" label-width="120" size="default"
        label-position="top">
        <el-row :gutter="20">
          <el-col :span="8" v-if="handleType != 'add'">
            <el-form-item label="转移单号" prop="location_code">
              {{ form.owner_transfer_order_no }}
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="仓库" prop="warehouse_id">
              <SelectWarehouse class="w-full" v-model="form.warehouse_id" :disabled="form.id" placeholder="请选择仓库">
              </SelectWarehouse>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="转移类型" prop="in_warehouse_id">
              <el-select class="w-full" v-model="form.type" :disabled="form.id" placeholder="请输入转移类型">
                <el-option v-for="item in props.options['cost.OwnerTransferOrder']?.[0].ownerTransferOrderType"
                  :key="item.value" :label="item.label" :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <vxe-table :data="form.detail" :round="true" height="300">
        <vxe-column title="SKU">
          <template #default="{ row }">
            <el-input v-model="row.sku" placeholder="输入SKU" @change="changeSkU(row)" :disabled="handleType == 'out'" />
          </template>
        </vxe-column>
        <vxe-column title="FNSKU">
          <template #default="{ row }">
            <el-select class="w-full" v-model="row.fn_sku" placeholder="FNSKU" :disabled="handleType == 'out'"
              @change="changeFNSKU($event,row)">
              <el-option v-for="item in row.fn_sku_list" :key="item.fn_sku" :label="item.fn_sku" :value="item.fn_sku">
              </el-option>
            </el-select>
          </template>
        </vxe-column>
        <vxe-column field="origin_owner" title="货主名称">
          <template #default="{ row }">
            <el-select class="w-full" v-model="row.origin_owner_id" placeholder="转移后货主" @change="changeOwner($event, row)"
              :disabled="handleType == 'out'">
              <el-option v-for="item in row.filter_owner" :key="item.owner_id" :label="item.owner_name" :value="item.owner_id">
              </el-option>
            </el-select>
          </template>
        </vxe-column>
        <vxe-column title="可转移数量">
          <template #default="{ row }">
            {{ row.can_transfer_num || '--' }}
          </template>
        </vxe-column>
        <vxe-column title="转移后货主">
          <template #default="{ row }">
            <select-personnel v-model="row.transfer_owner_id"></select-personnel>
          </template>
        </vxe-column>
        <vxe-column title="转移数量">
          <template #default="{ row }">
            <el-input v-model="row.num" placeholder="转移数量" />
          </template>
        </vxe-column>
        <vxe-column field="remark" title="备注">
          <template #default="{ row }">
            <el-input v-model="row.remark" placeholder="备注" />
          </template>
        </vxe-column>
        <vxe-column field="opearn" title="操作" width="100" v-if="handleType != 'view'">
          <template #default="{ row, rowIndex }">
            <el-link class="mr-2" size="small" type="primary" @click="addRow">新增</el-link>
            <el-link size="small" type="primary" @click="deleteRow(rowIndex)">删除</el-link>
          </template>
        </vxe-column>
      </vxe-table>
    </template>
    <template #footer>
      <template v-if="handleType == 'view'">
        <div class="flex justify-center py-2">
          <el-button type="primary" @click="close">关 闭</el-button>
        </div>
      </template>
      <template v-else>
        <div class="flex justify-center py-2">
          <el-button @click="close">取 消</el-button>
          <el-button v-if="handleType == 'out'" type="primary" @click="stockOut">出库</el-button>
          <el-button v-else type="primary" :loading="loading" @click="save(formRef)">保 存</el-button>
        </div>
      </template>
    </template>
  </el-dialog>
</template>
<script setup name="ComModal">
import { getOwnerTransferDetail, addOwnerTransfer } from '../api/index'
import { getSKULocation } from '@/api/public'
import { reactive, ref, toRefs } from 'vue'
import { ElMessage } from 'element-plus'
import SelectWarehouse from '@/components/SelectWarehouse'

const visible = ref(false)
const loading = ref(false)
const formRef = ref(null)
const emits = defineEmits(['query'])

const props = defineProps({
  options: {
    type: Array,
    default: [],
  },
})

const data = reactive({
  form: {},
  title: '新增',
  handleType: null,
  rules: {
    warehouse_id: [{
      required: true, message: '请选择仓库', trigger: 'blur'
    }],
    type: [{
      required: true, message: '请选择转移类型', trigger: 'blur'
    }],
  },
})
const { form, title, handleType, rules } = toRefs(data)

const statusMap = new Map([
  ['add', '新增'],
  ['edit', '编辑'],
  ['view', '查看'],
  ['out', '出库'],
])

const open = (type, id) => {
  title.value = statusMap.get(type)
  handleType.value = type
  visible.value = true
  if (id) getDetail(id)
}

const initForm = () => {
  form.value = getForm()
}
// 初始化
const getForm = () => {
  return {
    detail: [
      {
        sku: "",//sku
        custom_sku: "",//自定义sku
        base_sku_code: "",//商品编码
        location_id: "",//货位编码
        remark: "",//备注
      }
    ]
  }
}

onMounted(() => {
  initForm()
})

const getDetail = async (id) => {
  try {
    const res = await getOwnerTransferDetail({
      id
    })
    form.value = res.data
  } catch (e) {
    throw Error(e)
  }
}

const addRow = async () => {
  form.value.detail.push({
    sku: "",//sku
    custom_sku: "",//自定义sku
    base_sku_code: "",//商品编码
    location_code: "",//货位编码
    remark: "",//备注
  })
}

const deleteRow = (index) => {
  if (form.value.detail.length <= 1) return
  form.value.detail.splice(index, 1)
}



const changeSkU = async (row) => {
  if (!row.sku) {
    ElMessage.error('输入sku')
    return
  }
  if (!form.value.warehouse_id) {
    ElMessage.error('请选择仓库')
    return
  }
  if (!form.value.type) {
    ElMessage.error('请选择转移类型')
    return
  }
  try {
    const res = await getSKULocation({
      sku: row.sku,
      warehouse_id: form.value.warehouse_id,
      type: 1,
      owner_type: form.value.type,
      inv_type: ['owner_inv']
    })
    row.sku = res.data.sku
    row.owner = res.data.owner
    row.filter_owner = res.data.owner
    row.custom_sku = res.data.custom_sku
    row.sku_cn_title = res.data.sku_cn_title
    row.base_sku_code = res.data.base_sku_code
    row.fn_sku_list = res.data.fn_sku
  } catch (e) {
    throw Error(e)
  }
}

const changeOwner = (val, row) => {
  const checkItem = row.owner.find(item => item.owner_id == val)
  if (checkItem == undefined) return
  row.can_transfer_num = checkItem.num
  row.origin_owner = checkItem.owner_name
}

const changeFNSKU = (val, row) => {
  row.filter_owner = row.owner.filter(i => {
    if (i.fn_sku == val) {
      return i
    }
  })
}

const save = () => {
  if (!formRef.value) return
  formRef.value.validate((valid) => {
    if (valid) {
      loading.value = true

      const detail = form.value.detail.map(i => {
        return {
          sku: i.sku, //sku
          custom_sku: i.custom_sku, //自定义sku
          base_sku_code: i.base_sku_code, //商品编码
          origin_owner_id: i.origin_owner_id, //原货主id
          transfer_owner_id: i.transfer_owner_id, //转移货主id
          num: i.num, //转移数量
          remark: i.remark //备注
        }
      })
      addOwnerTransfer({
        // id: form.value.id,
        ...form.value,
        detail
      })
        .then((res) => {
          ElMessage.success(res.message)
          emits('query')
          close()
        })
        .finally((e) => {
          loading.value = false
        })
    }
  })
}

const stockOut = async () => {
  let formData = {}
  formData.id = form.value.id
  formData.detail = form.value.detail.map(i => {
    return {
      id: i.id,
      out_warehouse_num: i.out_warehouse_num
    }
  })
  try {
    const res = await outAdjustOut(formData)
    ElMessage.success(res.message)
    emits('query')
    close()
  } catch (e) {
    throw Error(e)
  }
}
const close = () => {
  initForm()
  visible.value = false
}
defineExpose({ open })
</script>
<style lang="scss" scoped>
.borderNone {
  :deep(.el-input__wrapper) {
    border: none;
    box-shadow: none
  }
}
</style>
